package org.jgs1904.dao.impl;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.jgs1904.dao.CommentDao;
import org.jgs1904.entity.Comment;
import org.jgs1904.util.DataSourceUtil;

import java.math.BigInteger;
import java.sql.SQLException;
import java.util.List;

/**
 * 评论数据操作类
 *
 * @author junki
 * @date 2020年3月26日
 */
public class CommentDaoImpl implements CommentDao {

    @Override
    public List<Comment> selectListByPostId(Long id) throws SQLException {
        QueryRunner qr = new QueryRunner(DataSourceUtil.getDataSource());

        String sql = "select comment.*,user.nickname from comment,user where comment.user_id = user.id and comment.post_id = ? order by comment.create_time desc";

        List<Comment> result = qr.query(sql, new BeanListHandler<>(Comment.class), id);

        return result;
    }


    @Override
    public Comment insert(Comment comment) throws SQLException {
        QueryRunner qr = new QueryRunner(DataSourceUtil.getDataSource());

        String sql = "insert into comment(user_id,post_id,content,create_time) value(?,?,?,?) ";

        BigInteger id = (BigInteger) qr.insert(sql, new ScalarHandler<>(1), comment.getUser_id(), comment.getPost_id(), comment.getContent(), comment.getCreate_time());

        comment.setId(id.longValue());

        return comment;
    }

}
